<template>
  <div class="talk-page">
    <PullRefresh @refresh="handleRefresh">
      <div class="talk-container">

          <n-space vertical>
            <!-- 发布说说按钮 -->
            <div class="publish-section">
              <n-button type="primary" size="large" @click="goToPublish">
                <template #icon>
                  <n-icon><AddIcon /></n-icon>
                </template>
                发布说说
              </n-button>
            </div>

            <!-- 说说列表 -->
            <div v-if="talkList.length > 0">
              <TalkCard
                v-for="talk in talkList"
                :key="talk.id"
                :talk="talk"
                @refresh="handleRefresh"
                @preview-video="previewVideo"
              />
            </div>

          <!-- 加载更多提示 -->
          <div v-if="loading" class="loading-more">
            <n-spin size="small" />
            <span>加载中...</span>
          </div>

          <div v-else-if="!hasMore && talkList.length > 0" class="no-more">
            <span>没有更多了</span>
          </div>

          <n-empty v-else-if="talkList.length === 0" description="暂无说说" />
        </n-space>
    </div>
    </PullRefresh>

    <!-- 悬浮菜单 -->
    <FloatingMenu
      :on-filter-change="handleFilterChange"
      :on-clear-filter="handleClearFilter"
    />

    <!-- 视频预览模态框 -->
    <n-modal
      :show="videoPreviewVisible"
      @update:show="closeVideoPreview"
      preset="card"
      style="width: 90vw; max-width: 800px"
      :mask-closable="true"
    >
      <div class="video-preview-content">
        <video
          v-if="previewVideoUrl"
          :src="previewVideoUrl"
          controls
          autoplay
          style="width: 100%; max-height: 70vh;"
        />
      </div>
    </n-modal>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, computed, h, onUnmounted } from 'vue'
import { useRouter } from 'vue-router'
import { useMessage, useDialog } from 'naive-ui'
import dayjs from 'dayjs'
import {
  Add as AddIcon,
  Play as PlayIcon
} from '@vicons/ionicons5'
import { talkApi } from '@/api/talk'
import { useUserStore } from '@/stores/user'
import PullRefresh from '@/components/common/PullRefresh.vue'
import FloatingMenu from '@/components/common/FloatingMenu.vue'
import TalkCard from '@/components/talk/TalkCard.vue'
import type { TalkItem } from '@/types/talk'

const router = useRouter()
const message = useMessage()
const dialog = useDialog()
const userStore = useUserStore()
const talkList = ref<TalkItem[]>([])
const loading = ref(false)
const hasMore = ref(true)
const currentPage = ref(1)
const pageSize = 10

// 视频预览相关
const videoPreviewVisible = ref(false)
const previewVideoUrl = ref('')

// 日期筛选相关
const dateFilter = ref<{
  type: 'month' | 'range'
  value: number | [number, number] | null
} | null>(null)

// 标签筛选相关
const tagFilter = ref<{
  tags: string[]
  mode: 'any' | 'all'
} | null>(null)

// 获取当前用户ID
const currentUserId = computed(() => userStore.userInfo?.id || 0)

// 格式化时间
const formatTime = (time: string) => {
  const now = dayjs()
  const talkTime = dayjs(time)
  const diffMinutes = now.diff(talkTime, 'minute')

  if (diffMinutes < 1) {
    return '刚刚'
  } else if (diffMinutes < 60) {
    return `${diffMinutes}分钟前`
  } else if (diffMinutes < 1440) {
    return `${Math.floor(diffMinutes / 60)}小时前`
  } else if (diffMinutes < 43200) {
    return `${Math.floor(diffMinutes / 1440)}天前`
  } else {
    return talkTime.format('MM-DD HH:mm')
  }
}

// 获取媒体网格样式类
const getMediaGridClass = (count: number) => {
  if (count === 1) return 'grid-1'
  if (count === 2) return 'grid-2'
  if (count === 3) return 'grid-3'
  if (count === 4) return 'grid-4'
  if (count === 5) return 'grid-5'
  if (count === 6) return 'grid-6'
  if (count === 7) return 'grid-7'
  if (count === 8) return 'grid-8'
  return 'grid-9'
}

// 跳转到发布页面
const goToPublish = () => {
  router.push('/talk/publish')
}

// 处理URL，智能处理HTTPS/HTTP
const processUrl = (url: string) => {
  // 如果是HTTPS链接，保持原样（不强制替换为HTTP）
  if (url.startsWith('https://')) {
    return url
  }
  // 如果是HTTP链接，也保持原样
  if (url.startsWith('http://')) {
    return url
  }
  // 如果是相对路径，添加协议
  if (url.startsWith('//')) {
    return `https:${url}` // 默认使用HTTPS
  }
  // 其他情况保持原样
  return url
}

// 判断是否为图片
const isImage = (photo: any) => {
  const fileType = photo.fileType || ''
  return fileType.startsWith('image/') ||
         photo.url.toLowerCase().match(/\.(jpg|jpeg|png|gif|webp|bmp)$/)
}

// 判断是否为视频
const isVideo = (photo: any) => {
  const fileType = photo.fileType || ''
  return fileType.startsWith('video/') ||
         photo.url.toLowerCase().match(/\.(mp4|avi|mov|wmv|flv|webm)$/)
}

// 预览视频
const previewVideo = (photo: any) => {
  console.log('预览视频函数被调用:', photo)
  console.log('视频URL:', photo.url)
  console.log('当前模态框状态:', videoPreviewVisible.value)
  previewVideoUrl.value = processUrl(photo.url)
  videoPreviewVisible.value = true
  console.log('设置后的模态框状态:', videoPreviewVisible.value)
}

// 关闭视频预览
const closeVideoPreview = () => {
  videoPreviewVisible.value = false
  previewVideoUrl.value = ''
}

// 播放视频（在网格中播放）
const playVideo = (event: Event, photo: any) => {
  event.stopPropagation()
  const video = event.target as HTMLVideoElement
  const container = video.parentElement

  if (video.paused) {
    // 播放视频
    video.play().then(() => {
      container?.classList.add('playing')
    }).catch((error) => {
      console.error('视频播放失败:', error)
      message.error('视频播放失败')
    })
  } else {
    // 暂停视频
    video.pause()
    container?.classList.remove('playing')
  }
}

// 视频播放结束
const onVideoEnded = (event: Event) => {
  const video = event.target as HTMLVideoElement
  const container = video.parentElement
  container?.classList.remove('playing')
}

// 查看说说详情
const viewTalkDetail = (talk: TalkItem) => {
  message.success('查看详情功能开发中...')
}

// 处理发布成功
const handlePublishSuccess = () => {
  message.success('发布成功！')
  // 重新获取说说列表
  fetchTalkList()
}

// 获取说说列表
const fetchTalkList = async (isLoadMore = false) => {
  if (loading.value || (!isLoadMore && !hasMore.value)) return

  try {
    loading.value = true

    // 构建请求参数
    const params: any = {
      pageNum: isLoadMore ? currentPage.value + 1 : 1,
      pageSize
    }

    // 添加日期筛选条件
    if (dateFilter.value) {
      console.log('日期筛选条件:', dateFilter.value)

      if (dateFilter.value.type === 'month' && dateFilter.value.value) {
        const monthTimestamp = dateFilter.value.value as number
        console.log('月份筛选时间戳:', monthTimestamp)
        // 将时间戳转换为dayjs对象，然后格式化为月份
        const monthDate = dayjs(monthTimestamp)
        const startDate = monthDate.startOf('month').format('YYYY-MM-DD HH:mm:ss')
        const endDate = monthDate.endOf('month').format('YYYY-MM-DD HH:mm:ss')
        params.startTime = startDate
        params.endTime = endDate
        console.log('月份时间范围:', startDate, '到', endDate)
            } else if (dateFilter.value.type === 'range' && dateFilter.value.value) {
        const [startTimestamp, endTimestamp] = dateFilter.value.value as [number, number]
        console.log('日期范围筛选时间戳:', startTimestamp, '到', endTimestamp)
        // 确保日期格式正确
        if (startTimestamp && endTimestamp) {
          // 将时间戳转换为dayjs对象
          const startDayjs = dayjs(startTimestamp)
          const endDayjs = dayjs(endTimestamp)

          if (startDayjs.isValid() && endDayjs.isValid()) {
            params.startTime = startDayjs.format('YYYY-MM-DD HH:mm:ss')
            params.endTime = endDayjs.format('YYYY-MM-DD HH:mm:ss')
            console.log('日期范围时间:', params.startTime, '到', params.endTime)
          } else {
            console.error('无效的日期格式:', startTimestamp, endTimestamp)
            message.error('日期格式无效')
            return
          }
        }
      }
    }

    // 添加标签筛选条件
    if (tagFilter.value) {
      console.log('标签筛选条件:', tagFilter.value)
      params.tags = tagFilter.value.tags
      params.tagMode = tagFilter.value.mode
      console.log('标签筛选参数:', params)
    }

    const response = await talkApi.getTalkList(params)
    console.log('API响应原始数据:', response)

    // 响应拦截器已经返回了 data 字段，所以直接访问 list
    const newList = response.list || []
    console.log('说说列表数据:', newList)

    // 检查每个说说的ID字段
    if (newList && newList.length > 0) {
      console.log('说说ID检查:')
      newList.forEach((talk, index) => {
        console.log(`说说${index + 1}:`, {
          id: talk.id,
          idType: typeof talk.id,
          content: talk.content?.substring(0, 20) + '...',
          fullTalk: talk
        })
      })
    }

    if (isLoadMore) {
      talkList.value.push(...newList)
      currentPage.value++
    } else {
      talkList.value = newList
      currentPage.value = 1
    }

    // 修复分页逻辑：直接检查返回的数据是否为空来判断是否还有更多数据
    // 如果返回的数据为空，说明已经到最后一页了
    hasMore.value = newList.length > 0

    // 添加调试信息
    console.log('分页调试信息:', {
      pageNum: isLoadMore ? currentPage.value : 1,
      pageSize,
      newListLength: newList.length,
      hasMore: hasMore.value,
      totalTalkListLength: talkList.value.length
    })
  } catch (error) {
    console.error('获取说说列表失败:', error)
    message.error('获取说说列表失败')
  } finally {
    loading.value = false
  }
}

// 下拉刷新
const handleRefresh = async () => {
  hasMore.value = true
  currentPage.value = 1
  await fetchTalkList(false)
}

// 处理筛选变化
const handleFilterChange = (filter: any) => {
  console.log('收到筛选变化:', filter)

  if (filter.type === 'tag') {
    // 标签筛选
    tagFilter.value = filter.value
    dateFilter.value = null
  } else {
    // 日期筛选
    dateFilter.value = filter
    tagFilter.value = null
  }

  hasMore.value = true
  currentPage.value = 1
  fetchTalkList(false)
}

// 清除筛选
const handleClearFilter = () => {
  dateFilter.value = null
  tagFilter.value = null
  hasMore.value = true
  currentPage.value = 1
  fetchTalkList(false)
}

// 懒加载检测
const handleScroll = () => {
  const scrollTop = window.pageYOffset || document.documentElement.scrollTop
  const windowHeight = window.innerHeight
  const documentHeight = document.documentElement.scrollHeight

  if (scrollTop + windowHeight >= documentHeight - 100 && hasMore.value && !loading.value) {
    fetchTalkList(true)
  }
}

onMounted(() => {
  fetchTalkList()
  window.addEventListener('scroll', handleScroll)
})

onUnmounted(() => {
  window.removeEventListener('scroll', handleScroll)
})
</script>

<style scoped>
.talk-container {
  max-width: 600px;
  margin: 0 auto;
  padding: 16px;
}

.talk-card {
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  margin-bottom: 16px;
}

.talk-card-top {
  border-left: 4px solid #ff6b35;
}

.talk-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 12px;
}

.user-info {
  display: flex;
  align-items: center;
  gap: 12px;
}

.user-details {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.nickname {
  font-weight: 600;
  font-size: 16px;
  color: #333;
}

.time {
  font-size: 12px;
  color: #999;
}

.talk-content {
  margin-bottom: 16px;
}

.talk-text {
  font-size: 15px;
  line-height: 1.6;
  color: #333;
  margin-bottom: 12px;
  word-wrap: break-word;
}

.talk-tags {
  margin-bottom: 12px;
}

.loading-more,
.no-more {
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 20px;
  color: #666;
  font-size: 14px;
  gap: 8px;
}

.talk-page {
  position: relative;
  min-height: 100vh;
}

.talk-media {
  margin-bottom: 12px;
}

.media-grid {
  display: grid;
  gap: 4px;
  border-radius: 8px;
  overflow: hidden;
  max-width: 100%;
}

.grid-1 {
  grid-template-columns: 1fr;
  max-width: 300px;
}

.grid-2 {
  grid-template-columns: 1fr 1fr;
  max-width: 400px;
}

.grid-3 {
  grid-template-columns: 1fr 1fr 1fr;
  max-width: 500px;
}

.grid-4 {
  grid-template-columns: 1fr 1fr;
  grid-template-rows: 1fr 1fr;
  max-width: 400px;
}

.grid-5 {
  grid-template-columns: 1fr 1fr 1fr;
  grid-template-rows: 1fr 1fr;
  max-width: 500px;
}

.grid-6 {
  grid-template-columns: 1fr 1fr 1fr;
  grid-template-rows: 1fr 1fr;
  max-width: 500px;
}

.grid-7 {
  grid-template-columns: 1fr 1fr 1fr;
  grid-template-rows: 1fr 1fr 1fr;
  max-width: 500px;
}

.grid-8 {
  grid-template-columns: 1fr 1fr 1fr;
  grid-template-rows: 1fr 1fr 1fr;
  max-width: 500px;
}

.grid-9 {
  grid-template-columns: 1fr 1fr 1fr;
  grid-template-rows: 1fr 1fr 1fr;
  max-width: 500px;
}

.media-item {
  aspect-ratio: 1;
  cursor: pointer;
  transition: opacity 0.3s ease;
  position: relative;
  overflow: hidden;
}

.media-item:hover {
  opacity: 0.8;
}

.media-image {
  width: 100%;
  height: 100%;
  border-radius: 4px;
  object-fit: cover;
}

.video-container {
  position: relative;
  width: 100%;
  height: 100%;
  border-radius: 4px;
  overflow: hidden;
  cursor: pointer;
}

.media-video {
  width: 100%;
  height: 100%;
  object-fit: cover;
  border-radius: 4px;
}

.video-overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.3);
  display: flex;
  align-items: center;
  justify-content: center;
  transition: opacity 0.3s ease;
}

.video-container:hover .video-overlay {
  opacity: 0.8;
}

.video-container.playing .video-overlay {
  opacity: 0;
}

.video-preview-content {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 200px;
}

.talk-footer {
  padding-top: 12px;
  border-top: 1px solid #f0f0f0;
}

.publish-section {
  margin-bottom: 20px;
  text-align: center;
}

.talk-actions {
  position: relative;
}

.media-overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.6);
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 4px;
}

.more-count {
  color: white;
  font-size: 18px;
  font-weight: bold;
}

.view-more {
  text-align: center;
  margin-top: 8px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .talk-container {
    padding: 8px;
  }

  .talk-card {
    border-radius: 8px;
  }

  .nickname {
    font-size: 15px;
  }

  .talk-text {
    font-size: 14px;
  }
}
</style>
